﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Medianamik.Core.DAL.SQL;

namespace Medianamik.Core.DAL
{
    public class UpdateNodePropertyValueCommandBuilder
    {
        private ParameterNameGenerator _paramGenerator = new ParameterNameGenerator();
        private JoinNameGenerator _joinGenerator = new JoinNameGenerator();
        private NodeProperty _prop;

        protected SubSonic.DataProvider Provider
        {
            get;
            private set;
        }

        public UpdateNodePropertyValueCommandBuilder(SubSonic.DataProvider pSubsonicDataProvider, NodeProperty pProp)
        {
            Provider = pSubsonicDataProvider;
            _prop = pProp;
        }


        public SubSonic.QueryCommand Build()
        {
            var queryParams = new List<IParameter>();

            var npvTable = new NodePropertyValueTable("npv");
            var valueParam = new Parameter(_paramGenerator.Next(), _prop.Value );
            queryParams.Add(valueParam);
            var setClauseList = new SetClauseList().Set(npvTable["Value"], new ParameterExpression(valueParam));
            var updateFrom = new UpdateFromClause(npvTable, setClauseList);

            var npvIdParam = new Parameter(_paramGenerator.Next(), _prop.ID);
            queryParams.Add(npvIdParam);
            var whereClause = new WhereClause()
                .AddPredicate(new ColumnPredicate(npvTable["NodePropertyValueId"], Medianamik.Core.Querying.Comparison.Equal, new ParameterExpression(npvIdParam)));
            var updateQuery = new UpdateQuery(updateFrom, whereClause);

            var command = new SubSonic.QueryCommand(updateQuery.ToSQL().ToString(), Provider.Name);
            foreach (var p in queryParams)
            {
                command.Parameters.Add(p.Name, p.Value);
            }
            return command;

        }
    }
}
